<template>
  <a-modal v-model:open="open" width="1200px" title="上传文件" @ok="handleOk">
    <a-form
      ref="formRef"
      :model="formState"
      name="validate_other"
      v-bind="formItemLayout"
      @finishFailed="onFinishFailed"
      @finish="onFinish"
    >
      <a-space
        v-for="(file, index) in formState.files"
        :key="file.id"
        style="display: flex; margin-bottom: 8px"
        align="baseline"
      >
        <a-form-item
          :label="`文件${index + 1}`"
          :name="['files', index, 'name']"
          style="width: 400px"
          :rules="{
            required: true,
            message: '请输入文件名'
          }"
        >
          <a-input v-model:value="file.name" placeholder="请输入文件名称" />
        </a-form-item>
        <a-form-item
          :name="['files', index, 'type']"
          :rules="{
            required: true,
            message: '请选择出库入库'
          }"
        >
          <a-radio-group v-model:value="file.type" button-style="solid">
            <a-radio-button value="入库">入库</a-radio-button>
            <a-radio-button value="出库">出库</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :name="['files', index, 'list']"
          :rules="{
            required: true,
            message: '请上传文件'
          }"
        >
          <a-upload
            v-model:fileList="file.list"
            :customRequest="customRequest"
            @change="(e: any) => handleChange(e, index)"
            accept="xlsx,xls,csv"
            name="logo"
            :maxCount="1"
            action="/upload.do"
          >
            <a-button>
              <template #icon>
                <UploadOutlined />
              </template>
              点击上传文件
            </a-button>
          </a-upload>
        </a-form-item>
        <DeleteOutlined @click="handleRemove(index)" />
      </a-space>
      <a-form-item v-bind="formItemLayoutWithOutLabel">
        <a-button type="dashed" block @click="handleAdd">
          <PlusOutlined />
          新增
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { UploadOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { XLSXUtil } from '../../utils/index'
const emit = defineEmits(['ok'])
const open = ref(false)
const formRef = ref<any>(null)

const formItemLayout = {
  // labelCol: { span: 6 },
  // wrapperCol: { span: 14 }
}

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 24, offset: 0 }
  }
}

const formState = reactive<{ files: Record<string, any>[] }>({
  files: []
})

const onFinish = (values: any) => {
  console.log('Success:', values)
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

const handleOk = async () => {
  await formRef?.value.validate()
  emit('ok', getDataSource())
  open.value = false
}

const handleAdd = () => {
  formState.files.push({
    type: null,
    name: `文件${formState.files.length + 1}`,
    list: []
  })
}

const handleChange = (event: any, index: number) => {
  console.log('event', event.file)
  XLSXUtil.getSourceData(event.file.originFileObj, ({ dataSource, columns }) => {
    formState.files[index] = {
      ...formState.files[index],
      name: event.file.name.split('.')[0] + index,
      dataSource,
      columns
    }
  })
}

const handleRemove = (index: number) => {
  formState.files.splice(index, 1)
}

const customRequest = async (options: any) => {
  const { onSuccess, onError, file, onProgress } = options
  Promise.resolve().then(() => {
    onSuccess('upload success')
  })
}

const getDataSource = () => {
  return formState.files.map((v) => ({
    ...v,
    dataSource: v.dataSource.map((item: any) => ({
      type: v.type,
      ...item
    }))
  }))
}

defineExpose({
  open: () => {
    open.value = true
  },
  getDataSource
})
</script>

<style lang="less" scoped></style>
